package com.battlebardgames.simplejavacache;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import com.battlebardgames.simplejavacache.cache.ICache;
import com.battlebardgames.simplejavacache.key.ICacheKeyProvider;

/**
 * Handles method invocations to proxied classes
 * @author Thomas Cashman
 */
public class CacheInvocationHandler implements InvocationHandler, Serializable {
	private static final long serialVersionUID = 1L;
	private Object m_object;
	
	/**
	 * Constructor
	 * @param cache Cache implementation
	 * @param obj Object instance
	 */
	public CacheInvocationHandler(Object obj) {
		m_object = obj;
	}
	
	/**
	 * Default constructor
	 */
	public CacheInvocationHandler() {}

	@Override
	public Object invoke(Object source, Method method, Object[] parameters)
			throws Throwable {
		String key = CacheEngine.getCacheKeyProvider().getCacheKey(m_object, method, parameters);
		if(!CacheEngine.getCache().contains(key)) {
			CacheEngine.getCache().set(key, method.invoke(m_object, parameters));
		}
		return CacheEngine.getCache().get(key);
	}
}
